<template>
  <img ref="imgRef" />
</template>

<script setup>
import QRcode from './qrcode'
import qrcodeProps from './props'

const props = defineProps(qrcodeProps)

const imgRef = ref(null)
const qrcode = ref(null)

watch(
  () => props.value,
  () => draw(),
)

onMounted(() => draw())

function initQRcode() {
  return new Promise((resolve) => {
    const p = props
    const el = document.createElement('div')
    new QRcode(el, {
      text: p.value,
      width: +p.size,
      height: +p.size,
      colorDark: p.colorDark,
      colorLight: p.colorLight,
      correctLevel: +p.correctLevel,
    })
    if (el.getElementsByTagName('canvas')[0]) {
      qrcode.value = el
      resolve()
    }
  })
}

function drawLogo() {
  return new Promise((resolve) => {
    const img = new Image()
    const p = props

    img.crossOrigin = 'anonymous'
    img.src = p.logo
    const logoPos = (+p.size - +p.logoSize) / 2
    const rectSize = +p.logoSize + +p.logoPadding
    const rectPos = (+p.size - rectSize) / 2
    const ctx = qrcode.value.getElementsByTagName('canvas')[0].getContext('2d')
    img.onload = () => {
      ctx.fillRect(rectPos, rectPos, rectSize, rectSize)
      ctx.drawImage(img, logoPos, logoPos, +p.logoSize, +p.logoSize)
      resolve()
    }
  })
}

async function draw() {
  await initQRcode()
  if (props.logo) {
    await drawLogo()
  }
  imgRef.value.src = qrcode.value.getElementsByTagName('canvas')[0].toDataURL('image/png')
}
</script>
